package sjd.ahsj.springbootmybatisplusoracle.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sjd.ahsj.springbootmybatisplusoracle.entity.*;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.BaseContextHandler;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.IgnoreAuth;
import sjd.ahsj.springbootmybatisplusoracle.model.AnimeInfo;
import sjd.ahsj.springbootmybatisplusoracle.model.Info;
import sjd.ahsj.springbootmybatisplusoracle.model.ReturnObject;
import sjd.ahsj.springbootmybatisplusoracle.service.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 动漫 前端控制器
 * </p>
 *
 * @author zhanghaogao
 * @since 2018-09-18
 */
@Api(description = "动漫")
@RestController
@RequestMapping("/anime")
public class AnimeController {
    @Autowired
    private IAnimeService iAnimeService;
    @Autowired
    private ISectionService iSectionService;
    @Autowired
    private IBaseUserService iBaseUserService;
    @Autowired
    private IAnimeBuyService iAnimeBuyService;
    @Autowired
    private IAnimeSubscriptionService iAnimeSubscriptionService;
    @Autowired
    private IAnimeReadService iAnimeReadService;


    @IgnoreAuth
    @ApiOperation("获取轮播")
    @RequestMapping(value = "/Carousel", method = RequestMethod.POST)

    public ReturnObject<List<Anime>> Carousel() {
        return new ReturnObject(0, "", iAnimeService.selectList(new EntityWrapper<Anime>().eq("carousel", 1)));
    }

    @IgnoreAuth
    @ApiOperation("动漫分页")
    @RequestMapping(value = "/amountBillPage", method = RequestMethod.POST)
    public ReturnObject<List<Anime>> amountBillPage(@RequestParam(defaultValue = "10") int limit,
                                                    @RequestParam(defaultValue = "1") int page,
                                                    @ApiParam("分类") String type,
                                                    @ApiParam("名称") String name,
                                                    @ApiParam("排序方式（up_time：更新时间,subscription_num：阅读量，read_num：订阅量）") @RequestParam(defaultValue = "up_time") String columns,
                                                    @ApiParam("是否正序") @RequestParam(defaultValue = "false") boolean isAsc) {
        EntityWrapper<Anime> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(type)) {
            ew.like("type", type);
        }
        if (StringUtils.isNotBlank(name)) {
            ew.like("name", name);
        }
        ew.orderBy(columns, isAsc);
        Page<Anime> pg = iAnimeService.selectPage(new Page<>(page, limit), ew);
        return new ReturnObject<>(0, "获取成功", pg.getTotal(), pg.getRecords());
    }

    @IgnoreAuth
    @ApiOperation("获取章节列表")
    @RequestMapping(value = "/amountInfo", method = RequestMethod.POST)
    public ReturnObject<AnimeInfo> amountInfo(@ApiParam("书籍id") Long animeId,
                                              @ApiParam("Token(没登陆就不传)") Long Token) {
        Anime anime = iAnimeService.selectById(animeId);
        Long read = null;
        List<Object> animeBuys = Lists.newArrayList();
        if (Token != null) {
            AnimeRead animeRead =
                    iAnimeReadService.selectOne(new EntityWrapper<AnimeRead>().eq("anime_id", animeId).eq("user_id",
                            Token));
            if (animeRead != null) {
                read = animeRead.getSection();
            }
            animeBuys = iAnimeBuyService.selectObjs(new EntityWrapper<AnimeBuy>().eq("user_id", Token).eq("anime_id",
                    animeId).setSqlSelect("section_id"));
        }

        int isSubscription = iAnimeSubscriptionService.selectCount(new EntityWrapper<AnimeSubscription>().eq(
                "anime_id", animeId).eq("user_id", Token));
        return new ReturnObject<>(0, "获取成功", new AnimeInfo(anime,
                iSectionService.selectList(new EntityWrapper<Section>().eq("anime_id", animeId)), read, animeBuys,
                isSubscription));
    }

    @ApiOperation("订阅、取消订阅动漫(必须登录)")
    @RequestMapping(value = "/subscription", method = RequestMethod.POST)
    public ReturnObject subscription(@ApiParam("书籍id") Long animeId,
                                     @ApiParam("类型（1：订阅，2：取消订阅）") Long type) {
        if (type == 1) {
            if (iAnimeSubscriptionService.selectCount(new EntityWrapper<AnimeSubscription>().eq("anime_id", animeId).eq(
                    "user_id", BaseContextHandler.getUserID())) > 0) {
                return new ReturnObject<>(1, "该漫画已订阅");
            }
            iAnimeSubscriptionService.insert(new AnimeSubscription(animeId, BaseContextHandler.getUserID()));
            return new ReturnObject<>(0, "订阅成功");
        }
        iAnimeService.delSubscription(animeId);
        iAnimeSubscriptionService.delete(new EntityWrapper<AnimeSubscription>().eq("anime_id", animeId).eq(
                "user_id", BaseContextHandler.getUserID()));
        return new ReturnObject<>(0, "取消订阅成功");

    }

    @ApiOperation("订阅列表")
    @RequestMapping(value = "/subscriptionList", method = RequestMethod.POST)
    public ReturnObject subscriptionList(@RequestParam(defaultValue = "10") int limit,
                                         @RequestParam(defaultValue = "1") int page) {
        EntityWrapper<Anime> ew = new EntityWrapper<>();
        List<Object> ids = iAnimeSubscriptionService.selectObjs(new EntityWrapper<AnimeSubscription>().eq("user_id",
                BaseContextHandler.getUserID()).setSqlSelect("anime_id"));
        if (ids.size() == 0) {
            return new ReturnObject<>(0, "获取成功", Lists.newArrayList());
        }
        ew.in("id", ids);
        ew.orderBy("up_time", false);

        return new ReturnObject<>(0, "获取成功", iAnimeService.selectPage(new Page<>(page, limit), ew)
                .getRecords());

    }


    @IgnoreAuth
    @ApiOperation("获取章节内容")
    @RequestMapping(value = "/sections", method = RequestMethod.POST)
    public ReturnObject<Info> sections(@ApiParam("章节id") Long sectionsId,
                                       @ApiParam("Token(没登陆就不传)") Long Token) {
        Section section = iSectionService.selectById(sectionsId);
        if (section.getAmount() != 0 && Token == null) {
            return new ReturnObject<>(2, "该章节为付费章节，请先登陆");
        }
        if (section.getAmount() > 0) {
            BaseUser user = iBaseUserService.selectById(Token);
            if (user.getMemberEndTime() == null || user.getMemberEndTime().getTime() < System.currentTimeMillis()) {
                if (iAnimeBuyService.selectCount(new EntityWrapper<AnimeBuy>().eq("user_id", Token).eq("section_id",
                        sectionsId)) == 0 && section.getAmount() != 0) {
                    //章节付费
                    if (!iAnimeBuyService.insert(new AnimeBuy(Token, section.getAnimeId(), sectionsId,
                            section.getAmount()))) {
                        return new ReturnObject<>(1, "余额不足，请充值后继续观看");
                    }

                }
            }
        }
        //增加阅读记录
        if (Token != null) {
            iAnimeReadService.delete(new EntityWrapper<AnimeRead>().eq("anime_id", section.getAnimeId()).eq("user_id"
                    , BaseContextHandler.getUserID()));
            iAnimeReadService.insert(new AnimeRead(section.getAnimeId(), sectionsId, BaseContextHandler.getUserID()));
        } else {
            iAnimeReadService.insert(new AnimeRead(section.getAnimeId(), sectionsId, null));
        }

        //获取上一章和下一章
        List<Section> list = iSectionService.selectList(new EntityWrapper<Section>().eq("anime_id",
                section.getAnimeId()));
        int sectionNum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == sectionsId.longValue()) {
                sectionNum = i;

            }
        }
        //获取下一章
        Long nextId = null;
        //获取上一章
        Long lastId = null;
        if (sectionNum != 0) {
            lastId = list.get(sectionNum - 1).getId();
        }
        if (sectionNum + 1 != list.size()) {
            nextId = list.get(sectionNum + 1).getId();
        }

        return new ReturnObject<>(0, "获取成功", new Info(JSONArray.parseArray(section.getContent(), String.class),
                nextId, lastId, section.getName(), section.getAnimeId()));
    }


}

